package com.xiaojie.consumer;


import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.xiaojie.entity.Order;
import com.xiaojie.mapper.OrderMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xiaojie
 * @version 1.0
 * @description: 补单消费者
 * @date 2021/10/11 22:37
 */
@Component
public class OrderConsumer {

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = {"xiaojie_order_queue"})
    /**
     * @description: 补单消费者，补偿分布式事务解决框架 数据最终一致性
     * @param:
     * @param: message
     * @param: channel
     * @return: void
     * @author xiaojie
     * @date: 2021/10/11 22:41
     */
    public void compensateOrder(Message message, Channel channel) throws IOException {
        // 1.获取消息
        String msg = new String(message.getBody());
        // 2.获取order对象
        Order orderEntity = JSONObject.parseObject(msg, Order.class);
        //根据订单号查询订单是否存在
        Order dbOrder = orderMapper.getOrder(orderEntity.getOrderId());
        if (dbOrder != null) {
            // 手动ack丢弃消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        //订单没有生成，开始补单
        int result = orderMapper.addOrder(orderEntity);
        if (result > 0) {
            // 手动ack 删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
